<template>
  <div class="warehouse-app">
    <!-- 头部区域 -->
    <div class="header">
      <h1 class="title">库存管理</h1>
      <div class="search-container">
        <div class="search-input-container">
          <input 
            v-model="searchTerm"
            @keyup.enter="performSearch"
            @input="onSearchInput"
            placeholder="请输入搜索关键词"
            class="search-input"
          />
          <button 
            @click="performSearch"
            :disabled="loading"
            class="search-btn"
          >
            {{ loading ? '搜索中...' : '搜索' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>正在搜索...</p>
    </div>

    <!-- 搜索结果 -->
    <div v-else-if="searchResults.length > 0 && searchPerformed" class="results-container">
      <!-- 结果统计和筛选按钮 -->
      <div class="results-header" v-if="shouldShowFilter">
        <div class="results-stats">
          <span class="results-count">
            <span v-if="selectedSupplier">"{{ selectedSupplier }}" 的商品: {{ filteredResults.length }} 个</span>
            <span v-else>全部商品: {{ filteredResults.length }} 个</span>
          </span>
          <span v-if="selectedSupplier" class="clear-filter" @click="clearSupplierFilter">
            清除筛选
          </span>
        </div>
        <button 
          @click="showSupplierFilter = true" 
          class="filter-btn"
          :class="{ 'active': selectedSupplier }"
        >
          🏢 供应商筛选
        </button>
      </div>
      
      <!-- 简单结果统计（非条码搜索或单供应商时） -->
      <div class="simple-results-header" v-else>
        <span class="results-count">找到 {{ filteredResults.length }} 个商品</span>
      </div>
      
      <!-- 商品列表 -->
      <ProductCard 
        v-for="item in filteredResults" 
        :key="item.id"
        :product="item"
        @openDateModal="openDateModal"
      />
    </div>

    <!-- 无结果提示 -->
    <div v-else-if="searchPerformed && !loading && searchResults.length === 0" class="no-results">
      <div class="no-results-icon">📦</div>
      <p>未找到相关库存信息</p>
      <small>请尝试其他关键词</small>
    </div>

    <!-- 供应商筛选弹窗 -->
    <SupplierFilter 
      :visible="showSupplierFilter"
      :search-results="searchResults"
      @close="showSupplierFilter = false"
      @select-supplier="handleSupplierSelection"
    />

    <!-- 生产日期修改弹窗 -->
    <DateEditModal 
      :visible="showDateEditModal"
      :product="selectedProduct"
      @close="closeDateModal"
      @submit="handleDateSubmit"
    />

    <!-- 调试面板 -->
    <DebugPanel ref="debugPanel" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { config, env, api } from "mdye";
import { API_CONFIG } from "../config/mingdao-config.js";
import ProductCard from "./components/ProductCard.vue";
import DebugPanel from "./components/DebugPanel.vue";
import SupplierFilter from "./components/SupplierFilter.vue";
import DateEditModal from "./components/DateEditModal.vue";
import { mockInventoryData, smartFilterMockData } from "./mockData.js";
import { 
  WORKSHEET_IDS, 
  VIEW_IDS, 
  buildSearchFilters, 
  transformInventoryData, 
  validateConfig,
  detectSearchType,
  MINGDAO_CONFIG 
} from "../config/mingdao-config.js";

// 系统初始化
console.log('移库管理系统初始化');

// 环境配置调试信息
console.log('环境配置候选来源(仅用于调试):', {
  'window.mdye.env.config': !!window?.mdye?.env?.config,
  'window.mdye.env': !!window?.mdye?.env,
  'window.env.config': !!window?.env?.config,
  'window.config': !!window?.config,
  'window.ming_config': !!window?.ming_config,
  'parent.ming_env.config': !!window?.parent?.ming_env?.config,
  'parent.ming_config': !!window?.parent?.ming_config,
  'parent.mdye.env.config': !!window?.parent?.mdye?.env?.config,
  'top.mdye.env.config': !!window?.top?.mdye?.env?.config
});

// 显示可用的配置键
if (window?.config) {
  console.log('window.config 可用键:', Object.keys(window.config));
}
if (window?.ming_config) {
  console.log('window.ming_config 可用键:', Object.keys(window.ming_config));
}
if (window?.parent?.config) {
  console.log('parent.config 可用键:', Object.keys(window.parent.config));
}
if (window?.parent?.ming_config) {
  console.log('parent.ming_config 可用键:', Object.keys(window.parent.ming_config));
}
if (window?.parent?.ming_env?.config) {
  console.log('parent.ming_env.config 可用键:', Object.keys(window.parent.ming_env.config));
}
if (window?.top?.config) {
  console.log('top.config 可用键:', Object.keys(window.top.config));
}

// 检查缺失的运行时配置
const missingConfigs = [];
const requiredConfigs = ['AppKey', 'Sign', 'LOCATION_STOCK', 'TRANSFER_ORDERS', 'LOCATION_MANAGEMENT'];

// 检查环境配置
const envRoot = window?.mdye?.env?.config || 
               window?.mdye?.env || 
               window?.env || 
               window?.ming_config ||
               window?.parent?.ming_env?.config ||
               window?.parent?.ming_config ||
               window?.parent?.mdye?.env?.config || 
               window?.top?.mdye?.env?.config ||
               window?.config ||
               window?.parent?.config ||
               window?.top?.config;
if (envRoot) {
  console.log('环境配置根对象:', envRoot);
  console.log('环境配置根对象键:', Object.keys(envRoot));
  requiredConfigs.forEach(key => {
    const value = envRoot[key];
    console.log(`检查配置项 ${key}:`, value);
    if (!value || value === '' || value === null || value === undefined) {
      missingConfigs.push(key);
    }
  });
} else {
  console.log('未找到环境配置根对象');
  missingConfigs.push(...requiredConfigs);
}

if (missingConfigs.length > 0) {
  console.warn('缺少运行时配置(不阻断初始化):', missingConfigs);
}

// 使用新的配置格式
const worksheetId = WORKSHEET_IDS.INVENTORY || config.worksheetId;
const viewId = VIEW_IDS.INVENTORY_DEFAULT || config.viewId;

// 检查API可用性
console.log('API状态检查:', {
  'mdye.api可用': !!api?.getFilterRows,
  'window.api可用': !!window?.api,
  'API_CONFIG.baseURL': API_CONFIG.baseURL,
  'API_CONFIG.appKey': !!API_CONFIG.appKey,
  'api对象内容': api
});

// 确保API函数可用
const getFilterRows = api?.getFilterRows || (() => {
  throw new Error('明道云API不可用！请确保在明道云插件环境中运行此应用。检查以下项目：\n1. window.api 是否存在\n2. mdye 包是否正确初始化\n3. 明道云插件环境是否正常');
});

// 初始化数据获取
console.log('开始获取可用商品列表...');
console.log('获取到 0 个商品:', []);
console.log('加载了 0 个商品');

console.log('获取移库单列表(使用明道云数据)...');
console.log('获取到 0 个移库单');
console.log('加载了 0 个移库单');

// 响应式数据
const searchTerm = ref('');
const searchResults = ref([]);
const filteredResults = ref([]); // 经过供应商筛选的结果
const loading = ref(false);
const searchPerformed = ref(false);
const debugPanel = ref(null);
const showSupplierFilter = ref(false); // 供应商筛选弹窗显示状态
const selectedSupplier = ref(''); // 当前选择的供应商
const showDateEditModal = ref(false); // 日期修改弹窗显示状态
const selectedProduct = ref(null); // 当前选择的商品


// 防抖定时器
let searchTimeout = null;

// 更新筛选结果
function updateFilteredResults() {
  if (!selectedSupplier.value) {
    // 没有选择供应商，显示所有结果
    filteredResults.value = searchResults.value;
  } else {
    // 根据选择的供应商筛选结果
    filteredResults.value = searchResults.value.filter(item => 
      item.supplier && item.supplier.trim() === selectedSupplier.value
    );
  }
  
  console.log('更新筛选结果:', {
    selectedSupplier: selectedSupplier.value,
    totalResults: searchResults.value.length,
    filteredResults: filteredResults.value.length
  });
}

// 处理供应商选择
function handleSupplierSelection(supplierName) {
  console.log('选择供应商:', supplierName);
  selectedSupplier.value = supplierName;
  updateFilteredResults();
}

// 清除供应商筛选
function clearSupplierFilter() {
  console.log('清除供应商筛选');
  selectedSupplier.value = '';
  updateFilteredResults();
}

// 判断是否应该显示供应商筛选功能（使用计算属性）
const shouldShowFilter = computed(() => {
  try {
    // 只有搜索条码且结果中有多个供应商时才显示
    if (!searchResults.value || searchResults.value.length === 0) return false;
    if (!searchTerm.value || !searchTerm.value.trim()) return false;
    
    const searchType = detectSearchType(searchTerm.value.trim());
    if (searchType !== 'barcode') return false;
    
    // 计算供应商数量
    const suppliers = new Set();
    searchResults.value.forEach(item => {
      if (item && item.supplier && item.supplier.trim()) {
        suppliers.add(item.supplier.trim());
      }
    });
    
    return suppliers.size > 1;
  } catch (error) {
    console.error('计算shouldShowFilter时出错:', error);
    return false;
  }
});

// 检查搜索结果中的供应商数量，按新逻辑决定是否显示筛选弹窗
function checkAndShowSupplierFilter() {
  try {
    if (!searchResults.value || searchResults.value.length === 0) return;
    if (!searchTerm.value || !searchTerm.value.trim()) return;
    
    // 检查搜索类型
    const searchType = detectSearchType(searchTerm.value.trim());
    console.log('检查供应商筛选条件 - 搜索类型:', searchType);
    
    // 只有搜索商品条码时才可能显示供应商筛选
    if (searchType !== 'barcode') {
      console.log('非条码搜索，不显示供应商筛选');
      return;
    }
    
    // 获取去重的供应商列表
    const suppliers = new Set();
    searchResults.value.forEach(item => {
      if (item && item.supplier && item.supplier.trim()) {
        suppliers.add(item.supplier.trim());
      }
    });
    
    console.log('检测到供应商数量:', suppliers.size);
    console.log('供应商列表:', Array.from(suppliers));
    
    // 只有多个供应商时才显示筛选弹窗
    if (suppliers.size > 1) {
      console.log('多个供应商，显示筛选弹窗');
      showSupplierFilter.value = true;
    } else if (suppliers.size === 1) {
      console.log('只有一个供应商，直接展示结果');
      // 单供应商情况下直接展示结果，不弹窗
    } else {
      console.log('没有供应商信息');
    }
  } catch (error) {
    console.error('检查供应商筛选时出错:', error);
  }
}

// 前端搜索结果过滤函数
function filterSearchResults(data, searchTerm) {
  if (!searchTerm || !searchTerm.trim() || !Array.isArray(data)) {
    return data;
  }
  
  const trimmedTerm = searchTerm.trim();
  const searchType = detectSearchType(trimmedTerm);
  
  console.log(`前端过滤 - 搜索词: "${trimmedTerm}", 类型: ${searchType}`);
  
  return data.filter(item => {
    if (searchType === 'location') {
      // 库位编码精确匹配
      const itemLocation = item.locationCode || '';
      const searchLocation = trimmedTerm;
      const isMatch = itemLocation.toLowerCase() === searchLocation.toLowerCase();
      console.log(`库位匹配检查:`);
      console.log(`  商品: ${item.productName || '未知'}`);
      console.log(`  商品库位: "${itemLocation}"`);
      console.log(`  搜索库位: "${searchLocation}"`);
      console.log(`  匹配结果: ${isMatch}`);
      return isMatch;
    } else if (searchType === 'barcode') {
      // 商品条码精确匹配
      const isMatch = item.barcode && item.barcode === trimmedTerm;
      console.log(`条码匹配: "${item.barcode}" === "${trimmedTerm}" -> ${isMatch}`);
      return isMatch;
    } else {
      // 通用搜索：商品名称模糊匹配 + 条码和库位编码精确匹配
      const nameMatch = item.productName && item.productName.toLowerCase().includes(trimmedTerm.toLowerCase());
      const barcodeMatch = item.barcode && item.barcode === trimmedTerm;
      const locationMatch = item.locationCode && item.locationCode.toLowerCase() === trimmedTerm.toLowerCase();
      
      const result = nameMatch || barcodeMatch || locationMatch;
      console.log(`通用搜索 "${item.productName}": 名称=${nameMatch}, 条码=${barcodeMatch}, 库位=${locationMatch} -> ${result}`);
      return result;
    }
  });
}

// 搜索输入处理（只清空结果，不自动搜索）
function onSearchInput() {
  clearTimeout(searchTimeout);
  if (!searchTerm.value.trim()) {
    searchResults.value = [];
    searchPerformed.value = false;
    return;
  }
  // 移除自动搜索，只有点击按钮时才搜索
}

// 执行搜索
async function performSearch() {
  if (!searchTerm.value.trim()) {
    searchResults.value = [];
    filteredResults.value = [];
    searchPerformed.value = false;
    selectedSupplier.value = '';
    showSupplierFilter.value = false;
    return;
  }

  loading.value = true;
  searchPerformed.value = true;

  // 验证配置
  const configValidation = validateConfig();
  if (!configValidation.isValid) {
    console.error('配置错误:', configValidation.errors);
    alert('配置错误：' + configValidation.errors.join(', ') + '\n请检查 config/mingdao-config.js 文件');
    loading.value = false;
    return;
  }

  try {
    // 开发模式或无工作表ID：使用示例数据
    if (!worksheetId || env.development) {
      console.log('使用示例数据进行智能搜索演示');
      console.log('工作表ID:', worksheetId);
      console.log('开发模式:', env.development);
      console.log('搜索关键词:', searchTerm.value);
      
      setTimeout(() => {
        // 使用前端过滤函数，确保逻辑一致
        const mockData = smartFilterMockData(searchTerm.value);
        searchResults.value = filterSearchResults(mockData, searchTerm.value.trim());
        console.log('模拟数据过滤结果:', searchResults.value.length, '条记录');
        
        // 重置供应商筛选并更新筛选结果
        selectedSupplier.value = '';
        updateFilteredResults();
        
        // 检查是否需要显示供应商筛选
        checkAndShowSupplierFilter();
        
        // 检查库位编码字段
        if (searchResults.value.length > 0) {
          console.log('模拟数据库位编码检查:');
          searchResults.value.forEach((item, idx) => {
            console.log(`  商品${idx + 1}: ${item.productName} - 库位: "${item.locationCode}"`);
          });
        }
        
        // 显示搜索类型信息
        const searchType = detectSearchType(searchTerm.value);
        console.log('搜索类型:', searchType);
        
        if (searchResults.value.length > 0) {
          console.log('找到的商品:', searchResults.value.map(item => ({
            name: item.productName,
            barcode: item.barcode,
            location: item.locationCode
          })));
        }
        
        loading.value = false;
      }, 800);
      return;
    }

    // 生产模式：调用明道云API
    console.log('调用明道云API搜索');
    console.log('工作表ID:', worksheetId);
    console.log('视图ID:', viewId);
    
    const filters = buildSearchFilters(searchTerm.value.trim());
    console.log('搜索过滤条件:', filters);
    
    if (filters.length === 0) {
      console.warn('未生成有效的搜索条件，请检查字段配置');
      searchResults.value = [];
      loading.value = false;
      return;
    }
    
    const requestParams = {
      worksheetId,
      viewId,
      filters,
      pageSize: 100,
      pageIndex: 1
    };
    
    console.log('API请求参数:', requestParams);
    
    const result = await getFilterRows(requestParams);
    console.log('API响应:', result);

    // 详细的响应数据检查
    console.log('API完整响应:', result);
    console.log('响应类型:', typeof result);
    console.log('响应是否为null/undefined:', result == null);
    
    if (result) {
      console.log('result.data存在性:', 'data' in result);
      console.log('result.data值:', result.data);
      console.log('result.data类型:', typeof result.data);
      
      if (result.data && Array.isArray(result.data)) {
        console.log('数据是数组，长度:', result.data.length);
        const transformedData = transformInventoryData(result.data);
        console.log('转换后的数据:', transformedData);
        
        // 前端二次过滤，确保搜索结果精确匹配
        const filteredData = filterSearchResults(transformedData, searchTerm.value.trim());
        console.log('前端过滤后的数据:', filteredData);
        
        // 检查API数据的库位编码字段
        if (filteredData.length > 0) {
          console.log('API数据库位编码检查:');
          filteredData.forEach((item, idx) => {
            console.log(`  商品${idx + 1}: ${item.productName} - 库位: "${item.locationCode}"`);
          });
        }
        
        searchResults.value = filteredData;
        
        // 重置供应商筛选并更新筛选结果
        selectedSupplier.value = '';
        updateFilteredResults();
        
        // 检查是否需要显示供应商筛选
        checkAndShowSupplierFilter();
      } else if (result.data === null || result.data === undefined) {
        console.warn('API返回的data字段为空');
        searchResults.value = [];
      } else {
        console.warn('API返回的data不是数组:', result.data);
        searchResults.value = [];
      }
    } else {
      console.warn('API返回结果为空:', result);
      searchResults.value = [];
    }
    
  } catch (error) {
    console.error('API搜索失败:', error);
    console.error('错误详情:', {
      message: error.message,
      stack: error.stack,
      worksheetId,
      viewId
    });
    
    // 显示错误信息给用户
    alert(`API调用失败: ${error.message}\n请检查:\n1. 网络连接\n2. 工作表ID是否正确\n3. 字段ID配置是否正确\n\n现在使用示例数据演示`);
    
    // API失败时回退到智能搜索示例数据
    console.log('回退到示例数据智能搜索');
    const fallbackData = smartFilterMockData(searchTerm.value);
    searchResults.value = filterSearchResults(fallbackData, searchTerm.value.trim());
    console.log('回退搜索结果:', searchResults.value.length, '条记录');
    
    // 重置供应商筛选并更新筛选结果
    selectedSupplier.value = '';
    updateFilteredResults();
    
    // 检查是否需要显示供应商筛选
    checkAndShowSupplierFilter();
  } finally {
    loading.value = false;
  }
}

// 打开日期修改弹窗
function openDateModal(product) {
  selectedProduct.value = product;
  showDateEditModal.value = true;
}

// 关闭日期修改弹窗
function closeDateModal() {
  showDateEditModal.value = false;
  selectedProduct.value = null;
}

// 处理日期修改提交
async function handleDateSubmit(webhookData) {
  try {
    console.log('准备发送webhook数据:', webhookData);
    
    // 发送webhook（动态读取配置）
    const webhookUrl = MINGDAO_CONFIG.webhookUrl || '';
    if (!webhookUrl) {
      alert('未配置 webhookUrl，请在 mdye.env.config 中设置变量 "webhookUrl"');
      return;
    }
    
    const response = await fetch(webhookUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(webhookData)
    });
    
    if (response.ok) {
      console.log('Webhook发送成功');
      alert('修改提交成功！');
      
      // 更新本地数据（可选）
      const productIndex = filteredResults.value.findIndex(p => p.id === webhookData.recordId);
      if (productIndex !== -1) {
        if (webhookData.newProductionDate) {
          filteredResults.value[productIndex].productionDate = webhookData.newProductionDate;
        }
        if (webhookData.modifiedQuantity !== null && webhookData.modifiedQuantity !== undefined) {
          filteredResults.value[productIndex].quantity = webhookData.modifiedQuantity;
          filteredResults.value[productIndex].availableStock = webhookData.modifiedQuantity;
        }
      }
      
      // 同时更新原始搜索结果
      const originalIndex = searchResults.value.findIndex(p => p.id === webhookData.recordId);
      if (originalIndex !== -1) {
        if (webhookData.newProductionDate) {
          searchResults.value[originalIndex].productionDate = webhookData.newProductionDate;
        }
        if (webhookData.modifiedQuantity !== null && webhookData.modifiedQuantity !== undefined) {
          searchResults.value[originalIndex].quantity = webhookData.modifiedQuantity;
          searchResults.value[originalIndex].availableStock = webhookData.modifiedQuantity;
        }
      }
      
    } else {
      console.error('Webhook发送失败:', response.status, response.statusText);
      alert('提交失败，请重试！');
    }
    
  } catch (error) {
    console.error('发送webhook时发生错误:', error);
    alert('提交失败，请检查网络连接！');
  } finally {
    closeDateModal();
  }
}

</script>

<style scoped>
/* 全局样式重置 */
* {
  box-sizing: border-box;
}

.warehouse-app {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  background-color: #f7f8fa;
  min-height: 100vh;
  color: #222;
  padding: 16px 16px 96px;
}

/* 头部样式 */
.header {
  background: #fff;
  border-radius: 16px;
  padding: 16px 18px;
  margin-bottom: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(0, 0, 0, 0.06);
}

.title {
  font-size: 18px;
  font-weight: 700;
  margin: 0 0 16px 0;
  text-align: center;
  color: #000000;
}

/* 搜索容器 */
.search-container {
  background: #fff;
  border-radius: 14px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(0, 0, 0, 0.06);
}

.search-input-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  flex: 1;
  padding: 12px 14px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 14px;
  font-size: 14px;
  background: #fff;
  color: #000000;
  transition: border-color 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #f8b300;
  box-shadow: 0 2px 12px rgba(248, 179, 0, 0.1);
}

.search-btn {
  height: 44px;
  padding: 0 24px;
  background: #f8b300;
  color: #000000;
  border: none;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.3s ease;
  letter-spacing: 1px;
}

.search-btn:hover:not(:disabled) {
  background: #e0a200;
  transform: translateY(-1px);
}

.search-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}


/* 加载状态 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #000000;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f0f0f0;
  border-top: 4px solid #f8b300;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 结果容器 */
.results-container {
  padding: 8px 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 结果头部 */
.results-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(0, 0, 0, 0.06);
  margin-bottom: 8px;
}

/* 结果统计 */
.results-stats {
  display: flex;
  align-items: center;
  gap: 16px;
}

.results-count {
  font-size: 15px;
  font-weight: 600;
  color: #000000;
}

.clear-filter {
  font-size: 14px;
  color: #f8b300;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.clear-filter:hover {
  background: #fefbf2;
  color: #e0a200;
}

/* 筛选按钮 */
.filter-btn {
  padding: 8px 16px;
  background: #f5f5f5;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #666666;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.filter-btn:hover {
  background: #e8e8e8;
  border-color: rgba(0, 0, 0, 0.12);
  color: #000000;
}

.filter-btn.active {
  background: #fefbf2;
  border-color: #f8b300;
  color: #000000;
}

.filter-btn.active:hover {
  background: #fdf5e6;
  border-color: #e0a200;
}

/* 简单结果头部 */
.simple-results-header {
  padding: 12px 16px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(0, 0, 0, 0.06);
  margin-bottom: 8px;
  text-align: center;
}

.simple-results-header .results-count {
  font-size: 15px;
  font-weight: 600;
  color: #000000;
}

/* 无结果提示 */
.no-results {
  background: #fff;
  border-radius: 16px;
  text-align: center;
  padding: 40px 20px;
  color: #000000;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(0, 0, 0, 0.06);
  margin-top: 14px;
}

.no-results-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.no-results p {
  font-size: 16px;
  margin: 0 0 8px 0;
  font-weight: 600;
  color: #000000;
}

.no-results small {
  font-size: 14px;
  color: #666666;
}


/* 移动端适配 */
@media (max-width: 768px) {
  .warehouse-app {
    padding: 12px 12px 80px;
  }
  
  .header {
    padding: 14px 12px;
    margin-bottom: 8px;
  }
  
  .title {
    font-size: 18px;
    margin-bottom: 12px;
  }
  
  .search-container {
    padding: 12px;
  }
  
  .search-input-container {
    gap: 10px;
  }
  
  .search-input {
    font-size: 16px;
    padding: 14px 16px;
    border-radius: 12px;
  }
  
  .search-btn {
    padding: 14px 20px;
    min-width: 80px;
    border-radius: 20px;
    font-size: 15px;
  }
  
  .results-container {
    padding: 8px 0;
    gap: 10px;
  }
  
  .results-header {
    padding: 10px 12px;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .results-stats {
    width: 100%;
    justify-content: space-between;
  }
  
  .results-count {
    font-size: 14px;
  }
  
  .clear-filter {
    font-size: 13px;
  }
  
  .filter-btn {
    align-self: flex-end;
    padding: 6px 12px;
    font-size: 13px;
  }
  
  .loading {
    padding: 40px 20px;
  }
}

@media (max-width: 480px) {
  .warehouse-app {
    padding: 8px 8px 80px;
  }
  
  .header {
    padding: 12px 8px;
  }
  
  .title {
    font-size: 16px;
    margin-bottom: 10px;
  }
  
  .search-container {
    padding: 8px;
  }
  
  .search-input-container {
    gap: 8px;
    flex-direction: column;
  }
  
  .search-input {
    font-size: 16px;
    padding: 12px 14px;
    width: 100%;
    border-radius: 10px;
  }
  
  .search-btn {
    padding: 12px 16px;
    font-size: 15px;
    width: 100%;
    border-radius: 18px;
    min-width: auto;
  }
  
  .results-container {
    gap: 8px;
  }
  
  .results-header {
    padding: 8px 12px;
  }
  
  .results-stats {
    gap: 8px;
    flex-direction: column;
    align-items: flex-start;
    width: 100%;
  }
  
  .results-count {
    font-size: 13px;
  }
  
  .clear-filter {
    font-size: 12px;
    align-self: flex-start;
  }
  
  .filter-btn {
    width: 100%;
    justify-content: center;
    padding: 8px 12px;
    font-size: 14px;
  }
  
  .loading {
    padding: 30px 15px;
  }
  
  .no-results {
    padding: 30px 15px;
    margin-top: 10px;
  }
  
  .no-results-icon {
    font-size: 40px;
    margin-bottom: 12px;
  }
}

/* 触摸优化 */
.search-btn,
.filter-btn,
.clear-filter {
  -webkit-tap-highlight-color: transparent;
  touch-action: manipulation;
}

.search-input {
  -webkit-tap-highlight-color: transparent;
}

/* 滚动优化 */
.warehouse-app {
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch;
  /* 确保搜索区域始终可见 */
  position: relative;
}

/* 防止iOS Safari缩放输入框 */
@supports (-webkit-touch-callout: none) {
  .search-input {
    font-size: 16px !important;
  }
}

/* 确保搜索按钮在所有设备上都可见 */
.search-input-container {
  position: relative;
  z-index: 1;
}

/* 移动端视口优化 */
@media (max-width: 480px) {
  .search-container {
    position: sticky;
    top: 0;
    background: #f7f8fa;
    z-index: 10;
    margin: -8px -8px 8px -8px;
    padding: 12px 8px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  }
  
  .header {
    position: sticky;
    top: 0;
    background: #f7f8fa;
    z-index: 9;
    margin: -8px -8px 0 -8px;
    padding: 12px 8px 0;
  }
}

/* 横屏适配 */
@media (max-width: 896px) and (orientation: landscape) {
  .warehouse-app {
    padding: 8px 12px 40px;
  }
  
  .header {
    padding: 8px 12px;
  }
  
  .title {
    font-size: 16px;
    margin-bottom: 8px;
  }
  
  .search-container {
    padding: 8px 12px;
  }
}
</style>